import os
import chardet

# kui-novel-arrange
# 奎歪歪的小说整理 脚本
# 编码检测

# 参数设置
directory_path = "txt" # 指定目录路径

def detect_encoding(file_path):
    with open(file_path, 'rb') as file:
        raw_data = file.read()
        result = chardet.detect(raw_data)
        encoding = result['encoding']
        confidence = result['confidence']
        return encoding, confidence

def print_file_encoding_table(directory):
    encoding_table = {}

    # 统计目录下的txt文件数量
    for filename in os.listdir(directory):
        if filename.endswith(".txt"):
            filepath = os.path.join(directory, filename)

            # 检测文件编码
            encoding, confidence = detect_encoding(filepath)
            if encoding is None:
                print(f"无法检测文件编码: {filename}")
                continue

            # 记录文件编码到编码表
            if encoding not in encoding_table:
                encoding_table[encoding] = 1
            else:
                encoding_table[encoding] += 1

    print("文件编码表:")
    for encoding, count in encoding_table.items():
        print(f"编码: {encoding}, 数量: {count}")

print_file_encoding_table(directory_path)